<template>
  <el-dialog
      :title="!dataForm.id ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible">
    <!--keyup.enter.native是回车事件，按下回车时触发-->
    <el-form :model="dataForm"  ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="80px">
      <el-form-item label="友链名称" prop="nickName">
        <el-input v-model="dataForm.nickname"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="dataForm.description"></el-input>
      </el-form-item>
      <el-form-item label="站点" prop="nickName">
        <el-input v-model="dataForm.website"></el-input>
      </el-form-item>
      <el-form-item label="头像URL" prop="avatar">
        <el-input v-model="dataForm.avatar" ></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      dataForm: {
        id: null,
        description:'',
        website:'',
        avatar:'',
        nickName: '',
        isPublished: true,
        views:0
      },

    }
  },
  methods: {
    init(id) {
      this.dataForm.id = id
      this.visible = true
      // dom元素更新后执行
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: `/friend/${this.dataForm.id}`,
            method: 'get',
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm=data.friend;
              this.dataForm.nickName = data.friend.nickname
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: `/friend/${!this.dataForm.id ? 'save' : 'update'}`,
            method: 'post',
            data: {
              'id': this.dataForm.id,
              'description': this.dataForm.description,
              'website':this.dataForm.website,
              'avatar':this.dataForm.avatar,
              'nickname':this.dataForm.nickname,
              'isPublished':this.dataForm.isPublished,
              'views':this.dataForm.views
            }
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
